import { Subscription, Reducer, Effect, Dispatch } from 'umi';
import { History } from 'history';
import { ConnectState } from './connect';
import { UserTypeState } from '@/pages/pricing/type';
import { decodeURIParams } from '@/public/utils/url';
export interface UserModelType {
  namespace: 'mainUserStore';
  state: UserTypeState;
  effects: {
    getUrlParams: Effect; // 获取用户信息
  };
  reducers: {
    saveData: Reducer<UserTypeState>;
  };
  subscriptions: { setup: Subscription };
}

const UserModel: UserModelType = {
  namespace: 'mainUserStore',
  state: {
    merchant: {},
    token: {},
    user: {
      number: '',
      orgId: '',
      post: '',
      userName: '',
      mobile: '',
      merchantId: '',
      storeCode:''
    },
  },

  effects: {
    *getUrlParams({ payload }, { call, put, select }) {
      const { user } = yield select((_: ConnectState) => _.mainUserStore);
      if (!user.number) {
        const { merchant, token, user } = decodeURIParams();
        yield put({
          type: 'saveData',
          payload: {
            merchant: merchant || {},
            token: token || {},
            user: user || {},
          },
        });
      }
    },
  },

  reducers: {
    saveData(state, { payload }) {
      return {
        ...payload,
      };
    },
  },
  subscriptions: {
    setup({ history, dispatch }: { history: History; dispatch: Dispatch }) {
      history.listen((location) => {
        dispatch({
          type: 'getUrlParams',
        });
      });
    },
  },
};

export default UserModel;
